from PIL import Image
import os
import shutil
import exifread

# 定义压缩图片并保留Exif信息的函数
def compress_image_with_exif(input_path, output_path, max_size=4 * 1024 * 1024):
    with Image.open(input_path) as img:
        img.save(output_path, optimize=True, quality=85)
        # 读取并保存Exif信息
        with open(output_path, 'rb') as img_file:
            tags = exifread.process_file(img_file)
        return tags

# 定义遍历文件夹并处理图片的函数
def process_images(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                file_path = os.path.join(root, file)
                file_size = os.path.getsize(file_path)
                max_size=4 * 1024 * 1024
                if file_size > max_size:
                    # 压缩图片并保留Exif信息
                    output_path = file_path + '.compressed'
                    tags = compress_image_with_exif(file_path, output_path)
                    # 打印处理结果
                    print(f"Compressed '{file}' to '{output_path}'. Size: {file_size} -> {os.path.getsize(output_path)} bytes. Tags: {tags}")
                    # 删除原始文件，保留压缩后的文件
                    os.remove(file_path)

# 替换成你要处理的文件夹路径
folder_path = 'pic'
process_images(folder_path)
